﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Xml.Linq;
using System.ServiceModel.Syndication;
using Robert.BlogUpdater.Properties;
using Robert.BlogUpdater.Classes;

namespace Robert.BlogUpdater
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private RSSFeedList feeds;
        private RSSFeedPostList posts;
        private SyndicationFeed synFeed;
        private bool feedAdded = false;
        private bool feedRemoved = false;
        private delegate void AddingFeedDelegate(string feedURL, RSSFeedList list);
        private delegate void ProgressDelegate(RSSFeed feed);
        private delegate void FeedSelectedDelegate(string feedURL);
        private delegate void FeedSummaryDelegate();

        public MainWindow()
        {
            InitializeComponent();
            #region ClearSettings()
            /*Settings.Default.FeedNames.Clear();
            Settings.Default.FeedNames.Clear();
            Settings.Default.FeedNumbers = 0;
            Settings.Default.FirstStart = false;
            Settings.Default.Save();*/
            #endregion
            #region FirstStart()
            if (!Settings.Default.FirstStart)
            {
                RSSFeedPostList firstFeeds = new RSSFeedPostList();
                RSSFeedPost firstFeed = new RSSFeedPost()
                {
                    PostTitle = "Welcome to Feed Tracker 0.1a",
                    PostSummary = "This is just a test post of a pseudo-feed. It will be removed when you add your own feeds...",
                    PostDate = DateTimeOffset.Now.ToString(),
                    PostURL = new Uri("http://feedtracker.codeplex.com")
                };
                firstFeeds.Add(firstFeed);
                feedTextList.DataContext = firstFeeds;
                Settings.Default["FirstStart"] = true;
                Settings.Default.Save();
            }
            else
            {
                feeds = RSSFeedList.Load();
                feedList.DataContext = feeds;
                RSSFeedPostList firstFeeds = new RSSFeedPostList();
                RSSFeedPost firstFeed = new RSSFeedPost()
                {
                    PostTitle = "Welcome to Feed Tracker 0.1a",
                    PostSummary = "Select one of your feeds to view it\n\n<--your feeds...",
                    PostDate = DateTimeOffset.Now.ToString(),
                    PostURL = new Uri("http://feedtracker.codeplex.com")
                };
                firstFeeds.Add(firstFeed);
                feedTextList.DataContext = firstFeeds;
            }
            #endregion
        }

        private void isEnterHit(object sender, KeyEventArgs e)
        {
            AddingFeedDelegate adder;
            if(e.Key == Key.Enter)
                adder = AddingFeedInvoke();
                
        }

        private void getFeedClick(object sender, RoutedEventArgs e)
        {
            AddingFeedDelegate adder = AddingFeedInvoke();
        }

        private AddingFeedDelegate AddingFeedInvoke()
        {
            AddingFeedDelegate adder;
            if (feedList.DataContext == null)
            {
                progressBar.IsIndeterminate = true;
                adder = new AddingFeedDelegate(this.AddFeedToList);
                adder.BeginInvoke(feedAddress.Text, null, null, null);
            }
            else
            {
                progressBar.IsIndeterminate = true;
                adder = new AddingFeedDelegate(this.AddFeedToList);
                adder.BeginInvoke(feedAddress.Text, (RSSFeedList)feedList.DataContext, null, null);
            }
            return adder;
        }
        
        private void AddFeedToList(string URL, RSSFeedList list)
        {
            
            var xDocument = XDocument.Load(URL);

            synFeed = SyndicationFeed.Load(xDocument.CreateReader());

            var feed = new RSSFeed()
            {
                FeedTitle = synFeed.Title.Text,
                FeedURL = URL
            };

            this.Dispatcher.BeginInvoke(new ProgressDelegate(UpdateProggresBar), System.Windows.Threading.DispatcherPriority.Normal, feed);

        }

        private void UpdateProggresBar(RSSFeed feed)
        {
            feeds.Add(feed);
            feedList.DataContext = feeds;
            progressBar.IsIndeterminate = false;
        }

        private void feedSelected(object sender, SelectionChangedEventArgs e)
        {
            FeedSelectedDelegate fSelect;
            if (feedList.SelectedItems.Count > 0)
            {
                fSelect = new FeedSelectedDelegate(this.FeedSelectedUpdate);
                fSelect.BeginInvoke((feedList.SelectedItem as RSSFeed).FeedURL, null, null);
            }
        }

        private void FeedSelectedUpdate(string feedURL)
        {
            var xDocument = XDocument.Load(feedURL);

            synFeed = SyndicationFeed.Load(xDocument.CreateReader());

            posts = RSSFeedPostList.Load(synFeed);

            this.Dispatcher.BeginInvoke(new FeedSummaryDelegate(UpdateSummary), System.Windows.Threading.DispatcherPriority.Normal);
        }

        private void UpdateSummary()
        {
            feedTextList.DataContext = posts;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (feedAdded || feedRemoved)
                feeds.Save(feeds);
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            var link = (Hyperlink)sender;
            Process.Start(link.NavigateUri.ToString());
        }

        private void removeFeed_Click(object sender, RoutedEventArgs e)
        {
            if (feedList.SelectedItems.Count > 0)
            {
                feeds = (RSSFeedList)feedList.DataContext;
                feeds.Remove(RSSFeedList.FindFeed(feedList.SelectedItem.ToString(), feeds));

                feedRemoved = true;
            }
        }
    }
}
